import { ExpertDelTime, ExpertMonth, ExpertTimes } from '@/api/expert';
import { Button, Icon, Tag } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import { AtCalendar } from 'taro-ui';
import 'taro-ui/dist/style/components/calendar.scss';
import { TemplateMessage } from 'types/user';
import useAdd from './components/useAdd';

export default function Page() {
  const [date, setDate] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const { data: bookedTimes, refresh: refreshBookedTimes } =
    useRequest(ExpertMonth);
  const marks = useMemo(
    () =>
      bookedTimes?.map((i) => ({
        value: dayjs(i).format('YYYY/MM/DD'),
      })),
    [bookedTimes]
  );

  const { data: times, refresh } = useRequest(() => ExpertTimes({ date }), {
    refreshDeps: [date],
    cacheKey: 'get:expert:times',
  });

  const { renderNode: renderAddNode, open: openAdd } = useAdd({
    curDate: date,
    times: times || [],
    onSuccess: () => {
      refresh();
      refreshBookedTimes();
    },
  });

  //删除预约时间
  const { runAsync: runDelAsync } = useRequest(ExpertDelTime, { manual: true });

  return (
    <>
      <View
        className=' pt-4 px-4 bg-white min-h-screen'
        style={{
          paddingBottom: 'calc(64px + env(safe-area-inset-bottom))',
        }}
      >
        <Text className=' text-sm block text-black mb-2'>
          您可以发布未来30天可预约的时间
        </Text>
        <AtCalendar
          marks={marks || []}
          className=' border-2 border-solid border-[#EFF3FA] mb-6 p-4 rounded-lg'
          minDate={dayjs().format('YYYY-MM-DD')}
          maxDate={dayjs().add(1, 'M').format('YYYY-MM-DD')}
          onDayClick={(e) => {
            setDate(e.value);
          }}
        />

        <View className='space-y-2'>
          {times?.map((item) => (
            <View
              className=' border-4 border-solid border-gary5 py-3 px-4 rounded-lg text-xs flex items-center'
              key={item.id}
            >
              {item.start_time}- {item.end_time}
              {item.status === 2 && (
                <Tag
                  textColor='white'
                  type='warning'
                  onClick={() => {
                    Taro.navigateTo({
                      url: `/pages/expert/appointment/detial?id=${item.order_id}`,
                    });
                  }}
                  className='ml-1'
                >
                  已预约
                </Tag>
              )}
              {item.status === 1 && (
                <Tag className=' ml-1'>您已设定待用户预约</Tag>
              )}
              {/* *已预约， 可以查看 */}
              {item.status === 2 && (
                <View
                  className=' text-primary ml-auto leading-none'
                  onClick={() => {
                    Taro.navigateTo({
                      url: `/pages/expert/appointment/detail?id=${item.id}`,
                    });
                  }}
                >
                  <Icon name='search' className=' align-[-2px] mr-1' />
                  查看
                </View>
              )}
              {/* *待预约可以删除 */}
              {item.status === 1 && (
                <View
                  className=' text-danger  ml-auto leading-none'
                  onClick={() => {
                    Taro.showModal({
                      title: '删除预约时间',
                      content: `可预约时间： ${item.start_time} - ${item.end_time} \n 是否确认删除预约时间？`,
                      success: async ({ confirm }) => {
                        if (!confirm) return;
                        await runDelAsync({ id: item.id });
                        refresh();
                        Taro.showToast({ title: '已删除' });
                      },
                    });
                  }}
                >
                  <Icon name='delete-o' className=' align-[-2px]' /> 删除
                </View>
              )}
            </View>
          ))}

          <Button
            onClick={async () => {
              //@ts-ignore
              await Taro.requestSubscribeMessage({
                tmplIds: [TemplateMessage.预约结果通知],
              });
              openAdd();
            }}
            className='bg-white border-dashed border-primary border-2 text-primary leading-[80px]'
            block
          >
            + 新增可预约时间
          </Button>
        </View>
      </View>

      {renderAddNode()}
    </>
  );
}
